console.log("version 1.5.0")
var G = {
    client: null,
    display: null,
    mouse: null,
    keyboard: null,
    touchScreen: null,
    touchPad: null,
    oskBoard: null,
}

var HcyTunnel = null

//离开页面时自动触发注销
window.onunload = function () {
    if (G.client != null) {
        G.client.disconnect();
    }
};
// 解析url中的参数
function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}
window.onload = function (ev) {
    console.log("1")
    //连接参数
    var connectionParam = getQueryVariable("connectionParam");
    //连接来源，1-内部连接，2-uam(企业版)
    var sourceType = getQueryVariable("sourceType");
    var loginname = getQueryVariable("loginname");
    connect(connectionParam,sourceType,loginname)
}

/**
 * 初始化client
 * @param tokenString myToken
 */
function connect(connectionParam,sourceType,loginname) {
    console.log("开始连接")
    var tunnelUrl = ("https:" === document.location.protocol ? "wss://" : "ws://") + window.location.host+"/gua";
    var tunnel = new Guacamole.WebSocketTunnel(tunnelUrl);
    var connectParameterString ="connectionParam=" + connectionParam +"&sourceType="+sourceType+"&width="+
        window.innerWidth+"&height=" + window.innerHeight+"&loginname="+loginname;
    console.log( "音频支持"+Guacamole.AudioPlayer.getSupportedTypes() )
    G.client = new Guacamole.Client(tunnel);
    G.display = G.client.getDisplay();
    document.getElementById("displayDIV").appendChild(G.display.getElement());
    console.log( connectParameterString )
    G.client.connect(connectParameterString);

    //状态变化绑定
    tunnel.onstatechange = function (state) {
        tunnelStageChange(state);
    }
    G.client.onstatechange = function (state) {
        clientStageChange(state);
    }
    G.client.onerror = function (state) {
        clientErrorChange(state);
    }
    G.client.onLogin = function (state) {
        loginChange(state);
    }

    //操控事件绑定
    G.mouse = newMouse();
    G.keyboard = newKeyboard();
    setKeyboardListening(true);
    G.touch = newTouchMode();
    G.client.onclipboard = function (stream, mimeType) {
        setClipBoard(stream, mimeType);
    };
    HcyTunnel = tunnel
}

function setClipBoard(stream, mimeType) {
    // console.log("Clip");
    // console.log(stream);
    // console.log(mimeType);
    var reader;
    // If the received data is text, read it as a simple string
    if (/^text\//.exec(mimeType)) {
        // console.log("搞事的是text剪貼板");
        reader = new Guacamole.StringReader(stream);
        // Assemble received data into a single string
        var data = '';
        reader.ontext = function textReceived(text) {
            data += text;
        };
        // Set clipboard contents once stream is finished
        reader.onend = function textComplete() {
            // console.log("data:" + data);
            updateClipboardTextarea(data);
        };
    }
    // Otherwise read the clipboard data as a Blob
    else {
        localLog("這個剪貼板不是string");
        reader = new Guacamole.BlobReader(stream, mimeType);
        reader.onend = function blobComplete() {
            console.log("reader.getBlob()" + reader.getBlob());
            // $rootScope.$apply(function updateClipboard() {
            //     managedClient.clipboardData = new ClipboardData({
            //         type: mimetype,
            //         data: reader.getBlob()
            //     });
            // });
        };
    }
}

function setKeyboardListening(flag) {
    if (!flag) {
        G.keyboard.onkeydown = null;
        G.keyboard.onkeyup = null;
    } else {
        G.keyboard.onkeydown = function (keyCode) {
            hotKey(keyCode);
            G.client.sendKeyEvent(1, keyCode);
            // hotKeyFx(keyCode);
        };
        G.keyboard.onkeyup = function (keyCode) {
            G.client.sendKeyEvent(0, keyCode);
            hotkeys[0] = 0;
        };
    }
}

var hotkeys = [];

function hotKey(keyCode) {
    if (keyCode === 65507 || keyCode === 65508) {
        hotkeys[0] = 1;
    }
    if (hotkeys[0] === 1 && keyCode === 118) {
        getClipContent();
    }
}

function newKeyboard() {
    return new Guacamole.Keyboard(document.documentElement);
}

function newMouse() {
    var mouse = new Guacamole.Mouse(G.display.getElement());
    mouse.onmousedown =
        mouse.onmouseup =
            mouse.onmousemove = function (mouseState) {
                var ms = new Guacamole.Mouse.State(
                    mouseState.x / G.display.getScale(),
                    mouseState.y / G.display.getScale(),
                    mouseState.left,
                    mouseState.middle,
                    mouseState.right,
                    mouseState.up,
                    mouseState.down
                );
                G.client.sendMouseState(ms);
                // Hide software cursor when mouse leaves display
                var pos_y = mouseState.y;
                if (pos_y < 0) {
                    G.display.showCursor(false);
                } else {
                    G.display.showCursor(true);
                }
            };
    return mouse;
}

function newTouchMode() {
    G.touchScreen = new Guacamole.Mouse.Touchscreen(G.display.getElement());
    G.touchPad = new Guacamole.Mouse.Touchpad(G.display.getElement());
    return setTouchMode(1);
}

function setTouchMode(touchMode) {
    var touch;
    var oldTouch;
    if (touchMode) {
        // "touchScreenMode":
        touch = G.touchScreen;
        oldTouch = G.touchPad;
        console.log(localLog("set touch screen mode"));
    } else {
        // "touchPadMode":
        touch = G.touchPad;
        oldTouch = G.touchScreen;
        console.log(localLog("set touch pad mode!"));
    }
    oldTouch.onmousedown =
        oldTouch.onmouseup =
            oldTouch.onmousemove = null;
    touch.currentState.x = oldTouch.currentState.x;
    touch.currentState.y = oldTouch.currentState.y;
    touch.onmousedown =
        touch.onmouseup =
            touch.onmousemove = function (mouseState) {
                var ms = new Guacamole.Mouse.State(
                    mouseState.x / G.display.getScale(),
                    mouseState.y / G.display.getScale(),
                    mouseState.left,
                    mouseState.middle,
                    mouseState.right,
                    mouseState.up,
                    mouseState.down);
                G.client.sendMouseState(ms);
            };
    return touch;
}

function loginChange(state) {
    console.log("loginChange:" + state);
}

function clientStageChange(state) {
    // let str = "clientStageChange:" + state
    // console.log(str);
    showClientStageNotification(state);
}

function tunnelStageChange(state) {
    // console.log("tunnelStageChange:" + state);
    showTunnelNotification(state);
}

function clientErrorChange(errorCode) {
    var message = errorMessage(errorCode);
    // console.log("err:" + message);
    showErrorNotification(message);
}

function errorMessage(code) {
    switch (code) {
        case 0 :
            return "SUCCESS";
        case 256 :
            return "UNSUPPORTED";
        case 512 :
            return "SERVER_ERROR";
        case 513 :
            return "SERVER_BUSY";
        case 514:
            return "UPSTREAM_TIMEOUT";
        case 515:
            return "UPSTREAM_ERROR";
        case 516:
            return "RESOURCE_NOT_FOUND";
        case 517:
            return "RESOURCE_CONFLICT";
        case 518:
            return "RESOURCE_CLOSED";
        case 519:
            return "UPSTREAM_NOT_FOUND";
        case 520:
            return "UPSTREAM_UNAVAILABLE";
        case 521:
            return "SESSION_CONFLICT";
        case 522:
            return "SESSION_TIMEOUT";
        case 523:
            return "SESSION_CLOSED";
        case 768:
            return "CLIENT_BAD_REQUEST";
        case 771:
            return "CLIENT_FORBIDDEN";
        case 776:
            return "CLIENT_TIMEOUT";
        case 781:
            return "CLIENT_OVERRUN";
        case 783:
            return "CLIENT_BAD_TYPE";
        case 797:
            return "CLIENT_TOO_MANY";
    }
}
